package utils

import (
	"golang.org/x/sys/windows"
	"log"
	"unsafe"
)

var (
	user32           = windows.NewLazySystemDLL("user32.dll")
	procSendInput    = user32.NewProc("SendInput")
	procSetCursorPos = user32.NewProc("SetCursorPos")
)

type MOUSEINPUT struct {
	dx          int32
	dy          int32
	mouseData   uint32
	dwFlags     uint32
	time        uint32
	dwExtraInfo uintptr
}

type INPUT struct {
	typeField uint32
	mi        MOUSEINPUT
}

const (
	INPUT_MOUSE          = 0
	MOUSEEVENTF_MOVE     = 0x0001
	MOUSEEVENTF_ABSOLUTE = 0x8000
	MOUSEEVENTF_LEFTDOWN = 0x0002
	MOUSEEVENTF_LEFTUP   = 0x0004
)

func SendMouseInput(flags, data, dx, dy int) {
	inp := INPUT{
		typeField: INPUT_MOUSE,
		mi: MOUSEINPUT{
			dx:        int32(dx),
			dy:        int32(dy),
			mouseData: uint32(data),
			dwFlags:   uint32(flags),
		},
	}

	ret, _, err := procSendInput.Call(
		1,
		uintptr(unsafe.Pointer(&inp)),
		unsafe.Sizeof(inp),
	)

	if ret == 0 {
		log.Fatalf("Failed to send mouse input: %v", err)
	}
}

func SetCursorPos(x, y int) bool {
	ret, _, _ := procSetCursorPos.Call(
		uintptr(x),
		uintptr(y),
	)
	return ret != 0
}

//func main() {
//	// 移动鼠标到屏幕位置(100, 200)
//	SetCursorPos(100, 200)
//
//	// 模拟鼠标左键按下和释放
//	sendMouseInput(MOUSEEVENTF_LEFTDOWN, 0, 0, 0)
//	sendMouseInput(MOUSEEVENTF_LEFTUP, 0, 0, 0)
//}
